package com.flyco.modules.ums.controller;

import java.io.UnsupportedEncodingException;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.shiro.SecurityUtils;
import com.flyco.poi.excel.ExcelImportUtil;
import com.flyco.poi.excel.def.NormalExcelConstants;
import com.flyco.poi.excel.entity.ExportParams;
import com.flyco.poi.excel.entity.ImportParams;
import com.flyco.poi.excel.view.EntityExcelView;
import com.flyco.common.system.vo.LoginUser;
import com.flyco.common.api.vo.Result;
import com.flyco.common.system.query.QueryGenerator;
import com.flyco.common.util.oConvertUtils;
import com.flyco.modules.ums.entity.UmsMemberLevelRights;
import com.flyco.modules.ums.entity.UmsMemberLevelBanner;
import com.flyco.modules.ums.entity.UmsMemberLevel;
import com.flyco.modules.ums.vo.UmsMemberLevelPage;
import com.flyco.modules.ums.service.IUmsMemberLevelService;
import com.flyco.modules.ums.service.IUmsMemberLevelRightsService;
import com.flyco.modules.ums.service.IUmsMemberLevelBannerService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import com.flyco.common.aspect.annotation.AutoLog;

 /**
 * @Description: 会员等级表
 * @Author: flyco
 * @Date:   2022-09-29
 * @Version: V1.0
 */
@Api(tags="会员等级表")
@RestController
@RequestMapping("/f/ums/umsMemberLevel")
@Slf4j
public class UmsMemberLevelController {
	@Autowired
	private IUmsMemberLevelService umsMemberLevelService;
	@Autowired
	private IUmsMemberLevelRightsService umsMemberLevelRightsService;
	@Autowired
	private IUmsMemberLevelBannerService umsMemberLevelBannerService;
	
	/**
	 * 分页列表查询
	 *
	 * @param umsMemberLevel
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "会员等级表-分页列表查询")
    @ApiOperation(value="会员等级表-分页列表查询", notes="会员等级表-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(UmsMemberLevel umsMemberLevel,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<UmsMemberLevel> queryWrapper = QueryGenerator.initQueryWrapper(umsMemberLevel, req.getParameterMap());
		Page<UmsMemberLevel> page = new Page<UmsMemberLevel>(pageNo, pageSize);
		IPage<UmsMemberLevel> pageList = umsMemberLevelService.page(page, queryWrapper);
		return Result.ok(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param umsMemberLevelPage
	 * @return
	 */
	@AutoLog(value = "会员等级表-添加")
	@ApiOperation(value="会员等级表-添加", notes="会员等级表-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody UmsMemberLevelPage umsMemberLevelPage) {
       UmsMemberLevel umsMemberLevel = new UmsMemberLevel();
		BeanUtils.copyProperties(umsMemberLevelPage, umsMemberLevel);
		umsMemberLevelService.save(umsMemberLevel);
		return Result.ok("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param umsMemberLevelPage
	 * @return
	 */
	@AutoLog(value = "会员等级表-编辑")
	@ApiOperation(value="会员等级表-", notes="会员等级表-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody UmsMemberLevelPage umsMemberLevelPage) {
		UmsMemberLevel umsMemberLevel = new UmsMemberLevel();
		BeanUtils.copyProperties(umsMemberLevelPage, umsMemberLevel);
		umsMemberLevelService.updateById(umsMemberLevel);
		return Result.ok("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "会员等级表-通过id删除")
	@ApiOperation(value="会员等级表-通过id删除", notes="会员等级表-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) Long id) {
		umsMemberLevelService.delMain(id);
		return Result.ok("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "会员等级表-批量删除")
	@ApiOperation(value="会员等级表-批量删除", notes="会员等级表-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
	    this.umsMemberLevelService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.ok("批量删除成功！");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "会员等级表-通过id查询")
	@ApiOperation(value="会员等级表-通过id查询", notes="会员等级表-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) Long id) {
		UmsMemberLevel umsMemberLevel = umsMemberLevelService.getById(id);
		return Result.ok(umsMemberLevel);
	}
	
	//===========================以下是子表信息操作相关API====================================
	
	/**
	 * 通过主表id查询会员等级权益表
	 *
  	 * @param umsMemberLevelRights
	 * @return
	 */
	@AutoLog(value = "会员等级权益表-通过主表id查询")
    @ApiOperation(value="会员等级权益表-通过主表id查询", notes="会员等级权益表-通过主表id查询")
	@GetMapping(value = "/listUmsMemberLevelRightsByMainId")
	public Result<?> listUmsMemberLevelRightsByMainId(UmsMemberLevelRights umsMemberLevelRights,
                								  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                								  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                								  HttpServletRequest req) {
        if(umsMemberLevelRights.getLevelId()!=null) {
            QueryWrapper<UmsMemberLevelRights> queryWrapper = QueryGenerator.initQueryWrapper(umsMemberLevelRights, req.getParameterMap());
            Page<UmsMemberLevelRights> page = new Page<UmsMemberLevelRights>(pageNo, pageSize);
            IPage<UmsMemberLevelRights> pageList =  umsMemberLevelRightsService.page(page, queryWrapper);
            return Result.ok(pageList);
        }else{
            return Result.ok();
        }
    }
	
	/**
     * 添加会员等级权益表
     *
     * @param umsMemberLevelRights
     * @return
     */
    @AutoLog(value = "会员等级权益表-添加")
    @ApiOperation(value="会员等级权益表-添加", notes="会员等级权益表-添加")
    @PostMapping(value = "/addUmsMemberLevelRights")
    public Result<?> addUmsMemberLevelRights(@RequestBody UmsMemberLevelRights umsMemberLevelRights) {
        umsMemberLevelRightsService.save(umsMemberLevelRights);
        return Result.ok("添加会员等级权益表成功！");
    }
    
    /**
     * 编辑会员等级权益表
     *
     * @param umsMemberLevelRights
     * @return
     */
    @AutoLog(value = "会员等级权益表-编辑")
    @ApiOperation(value="会员等级权益表-编辑", notes="会员等级权益表-编辑")
    @PutMapping("/editUmsMemberLevelRights")
    public Result<?> editUmsMemberLevelRights(@RequestBody UmsMemberLevelRights umsMemberLevelRights) {
        umsMemberLevelRightsService.updateById(umsMemberLevelRights);
        return Result.ok("编辑会员等级权益表成功！");
    }
    
    /**
     * 通过id删除会员等级权益表
     *
     * @param id
     * @return
     */
    @AutoLog(value = "会员等级权益表-通过id删除")
    @ApiOperation(value="会员等级权益表-通过id删除", notes="会员等级权益表-通过id删除")
    @DeleteMapping(value = "/deleteUmsMemberLevelRights")
    public Result<?> deleteUmsMemberLevelRights(@RequestParam(name = "id", required = true) String id) {
       umsMemberLevelRightsService.removeById(id);
        return Result.ok("删除会员等级权益表成功！");
    }
	
	/**
     * 批量删除会员等级权益表
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "会员等级权益表-批量删除")
    @ApiOperation(value="会员等级权益表-批量删除", notes="会员等级权益表-批量删除")
    @DeleteMapping(value = "/deleteBatchUmsMemberLevelRights")
    public Result<?> deleteBatchUmsMemberLevelRights(@RequestParam(name = "ids", required = true) String ids) {
        if (ids == null || "".equals(ids.trim())) {
            return Result.error("参数不识别！");
        } 
        this.umsMemberLevelRightsService.removeByIds(Arrays.asList(ids.split(",")));
       	return Result.ok("批量删除成功！");

    }
    
	/**
	 * 通过主表id查询会员等级广告表
	 *
  	 * @param umsMemberLevelBanner
	 * @return
	 */
	@AutoLog(value = "会员等级广告表-通过主表id查询")
    @ApiOperation(value="会员等级广告表-通过主表id查询", notes="会员等级广告表-通过主表id查询")
	@GetMapping(value = "/listUmsMemberLevelBannerByMainId")
	public Result<?> listUmsMemberLevelBannerByMainId(UmsMemberLevelBanner umsMemberLevelBanner,
                								  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                								  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                								  HttpServletRequest req) {
        if(umsMemberLevelBanner.getLevelId()!=null) {
            QueryWrapper<UmsMemberLevelBanner> queryWrapper = QueryGenerator.initQueryWrapper(umsMemberLevelBanner, req.getParameterMap());
            Page<UmsMemberLevelBanner> page = new Page<UmsMemberLevelBanner>(pageNo, pageSize);
            IPage<UmsMemberLevelBanner> pageList =  umsMemberLevelBannerService.page(page, queryWrapper);
            return Result.ok(pageList);
        }else{
            return Result.ok();
        }
    }
	
	/**
     * 添加会员等级广告表
     *
     * @param umsMemberLevelBanner
     * @return
     */
    @AutoLog(value = "会员等级广告表-添加")
    @ApiOperation(value="会员等级广告表-添加", notes="会员等级广告表-添加")
    @PostMapping(value = "/addUmsMemberLevelBanner")
    public Result<?> addUmsMemberLevelBanner(@RequestBody UmsMemberLevelBanner umsMemberLevelBanner) {
        umsMemberLevelBannerService.save(umsMemberLevelBanner);
        return Result.ok("添加会员等级广告表成功！");
    }
    
    /**
     * 编辑会员等级广告表
     *
     * @param umsMemberLevelBanner
     * @return
     */
    @AutoLog(value = "会员等级广告表-编辑")
    @ApiOperation(value="会员等级广告表-编辑", notes="会员等级广告表-编辑")
    @PutMapping("/editUmsMemberLevelBanner")
    public Result<?> editUmsMemberLevelBanner(@RequestBody UmsMemberLevelBanner umsMemberLevelBanner) {
        umsMemberLevelBannerService.updateById(umsMemberLevelBanner);
        return Result.ok("编辑会员等级广告表成功！");
    }
    
    /**
     * 通过id删除会员等级广告表
     *
     * @param id
     * @return
     */
    @AutoLog(value = "会员等级广告表-通过id删除")
    @ApiOperation(value="会员等级广告表-通过id删除", notes="会员等级广告表-通过id删除")
    @DeleteMapping(value = "/deleteUmsMemberLevelBanner")
    public Result<?> deleteUmsMemberLevelBanner(@RequestParam(name = "id", required = true) String id) {
       umsMemberLevelBannerService.removeById(id);
        return Result.ok("删除会员等级广告表成功！");
    }
	
	/**
     * 批量删除会员等级广告表
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "会员等级广告表-批量删除")
    @ApiOperation(value="会员等级广告表-批量删除", notes="会员等级广告表-批量删除")
    @DeleteMapping(value = "/deleteBatchUmsMemberLevelBanner")
    public Result<?> deleteBatchUmsMemberLevelBanner(@RequestParam(name = "ids", required = true) String ids) {
        if (ids == null || "".equals(ids.trim())) {
            return Result.error("参数不识别！");
        } 
        this.umsMemberLevelBannerService.removeByIds(Arrays.asList(ids.split(",")));
       	return Result.ok("批量删除成功！");

    }
    

    /**
    * 导出excel
    *
    * @param request
    * @param umsMemberLevel
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, UmsMemberLevel umsMemberLevel) {
      // Step.1 组装查询条件
      QueryWrapper<UmsMemberLevel> queryWrapper = QueryGenerator.initQueryWrapper(umsMemberLevel, request.getParameterMap());
      LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

      //Step.2 获取导出数据
      List<UmsMemberLevelPage> pageList = new ArrayList<UmsMemberLevelPage>();
      List<UmsMemberLevel> umsMemberLevelList = umsMemberLevelService.list(queryWrapper);
      for (UmsMemberLevel temp : umsMemberLevelList) {
          UmsMemberLevelPage vo = new UmsMemberLevelPage();
          BeanUtils.copyProperties(temp, vo);
          List<UmsMemberLevelRights> umsMemberLevelRightsList = umsMemberLevelRightsService.selectByMainId(temp.getId());
          vo.setUmsMemberLevelRightsList(umsMemberLevelRightsList);
          List<UmsMemberLevelBanner> umsMemberLevelBannerList = umsMemberLevelBannerService.selectByMainId(temp.getId());
          vo.setUmsMemberLevelBannerList(umsMemberLevelBannerList);
          pageList.add(vo);
      }
      //Step.3 调用AutoPoi导出Excel
      ModelAndView mv = new ModelAndView(new EntityExcelView());
      mv.addObject(NormalExcelConstants.FILE_NAME, "会员等级表");
      mv.addObject(NormalExcelConstants.CLASS, UmsMemberLevelPage.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("会员等级表数据", "导出人:"+sysUser.getRealname(), "会员等级表"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
    }

    /**
    * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          MultipartFile file = entity.getValue();// 获取上传文件对象
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<UmsMemberLevelPage> list = ExcelImportUtil.importExcel(file.getInputStream(), UmsMemberLevelPage.class, params);
              for (UmsMemberLevelPage page : list) {
                  UmsMemberLevel po = new UmsMemberLevel();
                  BeanUtils.copyProperties(page, po);
                  umsMemberLevelService.saveMain(po, page.getUmsMemberLevelRightsList(),page.getUmsMemberLevelBannerList());
              }
              return Result.ok("文件导入成功！数据行数:" + list.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.ok("文件导入失败！");
    }
}
